<template>
  <KButton style="color:#999999" class="countdown-button" :loading="loading" :disabled="loading" @click="toAction">
    <span v-if="btnCount===0">{{text}}</span>
    <span v-else>{{actionText||text}}({{btnCount}})</span>
  </KButton>
</template>

<script>
  export default {
    props: {
      text: String,
      actionText: String,
      beforeClickFun: Function,
      count: {
        type: Number,
        default: 10
      }
    },

    data() {
      return {
        loading: false,
        timer: null,
        btnCount: 0
      };
    },

    beforeDestroy() {
      this.clearCountRun();
    },

    methods: {
      toAction() {
        if (this.loading) {
          return;
        }

        let beforeClickFun = this.beforeClickFun;
        if (beforeClickFun === undefined) {
          this.loading = true;
          this.toRunTimer();
          return;
        }
        

        this.loading = true;
        beforeClickFun().then(flag => {
          if (flag) {
            this.toRunTimer();
          } else {
            this.loading = false;
          }
        }).catch(function () {
          this.loading = false;
        });
      },

      toRunTimer(){
        this.clearCountRun();
        
        this.btnCount = this.count;
        this.timer = setInterval(() => {
          let btnCount = this.btnCount;
          btnCount--;
          this.btnCount = btnCount;
          if (btnCount === 0) {
            this.clearCountRun();
            this.loading = false;
          }
        }, 1000);
      },

      clearCountRun() {
        let timer = this.timer;
        if (timer !== null) {
          clearInterval(timer);
        }
      },

      resetBtn() {
        this.clearCountRun();
        this.loading = false;
        this.btnCount = 0;
      }
    }
  };

</script>

<style lang="scss">
  .weui-btn.countdown-button,
  .weui-btn.weui-btn_disabled.countdown-button {
    width: 100%;
    height: formatPx(90);
    border-radius: formatPx(45);
    border: none;
    background: #f7f7f7;
    font-size: formatPx(26);
    padding: 0;
    line-height: formatPx(90);
    font-weight: normal;
  }

</style>
